package com.boc.ewr.bcimp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.boc.ewr.bcimp.entity.HolidayList;
import com.boc.ewr.bcimp.mapper.HolidayListMapper;
import com.boc.ewr.bcimp.service.IHolidayListService;
import com.boc.ewr.util.file.enumeration.HolidayTypeEnum;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.*;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;

/**
 * @Description: 节假日清单
 * @Author: jeecg-boot
 * @Date:   2023-06-01
 * @Version: V1.0
 */
@Service
public class HolidayListServiceImpl extends ServiceImpl<HolidayListMapper, HolidayList> implements IHolidayListService {

    @Override
    public long countWorkdays(Date startDate, Date endDate) {
        LocalDate start = dateToLocalDate(startDate);
        LocalDate end = dateToLocalDate(endDate);
        long workdayCount = 0;
        LocalDate date = start;
        while (date.isBefore(end)) {
            if (isWeekend(date)) {
                if (isCompensatoryLeaveDay(date)) {
                    workdayCount++;
                }
            } else {
                if (!isHoliday(date)) {
                    workdayCount++;
                }
            }
            date = date.plus(1, ChronoUnit.DAYS);
        }
        return workdayCount;
    }

    private  LocalDate dateToLocalDate(Date date) {
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zoneId);
        return localDateTime.toLocalDate();
    }

    // 判断日期是否为法定节假日
    private  boolean isHoliday(LocalDate date) {
        List<HolidayList> holidayLists = this.list(
                new LambdaQueryWrapper<HolidayList>()
                        .eq(HolidayList::getHolidayType, HolidayTypeEnum.HOLIDAY.getIndex())
        );
        for (HolidayList holidayList : holidayLists) {
            if (date.isEqual(this.dateToLocalDate(holidayList.getHolidayDate()))) {
                return true;
            }
        }
        return false;
    }

    // 判断日期是否调休
    private  boolean isCompensatoryLeaveDay(LocalDate date) {
        List<HolidayList> holidayLists = this.list(
                new LambdaQueryWrapper<HolidayList>()
                        .eq(HolidayList::getHolidayType, HolidayTypeEnum.HOLIDAY.getIndex())
        );
        for (HolidayList holidayList : holidayLists) {
            if (date.isEqual(this.dateToLocalDate(holidayList.getHolidayDate()))) {
                return true;
            }
        }
        return false;
    }

    // 判断日期是否为周末
    private  boolean isWeekend(LocalDate date) {
        DayOfWeek dow = date.getDayOfWeek();
        return dow == DayOfWeek.SATURDAY || dow == DayOfWeek.SUNDAY;
    }
}
